//
//  UploadWork.m
//  SoundPill
//
//  Created by 宋旭东 on 15/11/5.
//  Copyright © 2015年 宋旭东. All rights reserved.
//

#import "UploadWork.h"
#import "AppDelegate.h"
@interface UploadWork ()
{
    int i;
    NSString *_workSpace;
    NSString *_workTime;
    NSNumber *_isPrivate;
    NSNumber *_tag_audioSecond;
    AudioUploadState *state;
}
@property (strong, nonatomic) NSMutableDictionary *allInfo;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *tags;
@end

@implementation UploadWork
- (instancetype)initWithWorkTime:(NSString *)workTime workSpace:(NSString *)workSpace tag_imageNameArray:(NSMutableArray *)imageNameArray tag_imagePathArray:(NSMutableArray *)imagePathArray tag_uploadImageArray:(NSMutableArray *)tag_uploadImageArray tag_imageArray:(NSArray *)tag_imageArray workname:(NSString *)workName audioSecond:(NSNumber *)audioSecond Private:(NSNumber *)Private
{
    self = [super init];
    if (self) {
        _workTime = workTime;
        _workSpace = workSpace;
        self.name = workName;
        _tag_audioSecond = audioSecond;
        _isPrivate = Private;
        self.allInfo = [[NSMutableDictionary alloc] init];
        self.tagArray = [[NSMutableArray alloc] init];
        self.tag_textArray = [[NSMutableArray alloc] init];
        self.tag_personArray = [[NSMutableArray alloc] init];
        self.tag_imageArray = tag_imageArray;
        self.tag_imageNameArray = imageNameArray;
        self.tag_imagePathArray = imagePathArray;
        self.tag_uploadImageArray = tag_uploadImageArray;
    }
    return self;
}
#pragma mark -
#pragma mark 上传音频
- (void)UpLoad:(NSString *)audioPath wavePath:(NSString *)wavePath{
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"type"];
    [manager GET:@"http://pillele.cn/api/uptoken" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        NSString *token = [dic objectForKey:@"token"];
        [self putAudioFileToQN:audioPath token:token];
        [self putWaveForm:wavePath token:token];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
//向七牛上传音频文件
- (void)putAudioFileToQN:(NSString *)audioPath token:(NSString *)token
{
    NSMutableDictionary *optionDic = [NSMutableDictionary dictionary];
    [optionDic setObject:@"1" forKey:@"x:type"];
    [optionDic setObject:[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] forKey:@"x:uid"];

//    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:nil params:optionDic checkCrc:NO cancellationSignal:nil];
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        if (percent < 0.9) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadPercent" object:[NSNumber numberWithFloat:percent]];
        }
    } params:optionDic checkCrc:NO cancellationSignal:nil];
    
    QNUploadManager *manager = [[QNUploadManager alloc] init];
    state = [AudioUploadState sharedInstance];
    [manager putFile:audioPath key:[NSString stringWithFormat:@"%@.mp3", _workTime] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        //        NSLog(@"音频:%@", resp);
        if (resp == nil) {
            //            NSLog(@"上传失败");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"uploadState" object:@"false"];
        } else {
            state.uploadId = [resp valueForKey:@"uploadId"];
            state.url = [resp valueForKey:@"url"];
            state.state = @"success";
            NSString *statePath =[_workSpace stringByAppendingPathComponent:@"workState"];
            [NSKeyedArchiver archiveRootObject:state toFile:statePath];
            [self UpLoadImageNameArray:_tag_imageNameArray ImagePathArray:_tag_imagePathArray];
        }
    } option:option];
}
- (void)putWaveForm:(NSString *)waveForm token:(NSString *)token
{
    NSMutableDictionary *optionDic = [NSMutableDictionary dictionary];
    [optionDic setObject:@"1" forKey:@"x:type"];
    [optionDic setObject:[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] forKey:@"x:uid"];
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:nil params:optionDic checkCrc:NO cancellationSignal:nil];
//    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
//        if (percent >= 0.8 && percent < 0.9) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadPercent" object:[NSNumber numberWithFloat:percent]];
//        }
//    } params:optionDic checkCrc:NO cancellationSignal:nil];

//    AudioUploadState *state = [AudioUploadState sharedInstance];
    QNUploadManager *manager = [[QNUploadManager alloc] init];
    [manager putFile:waveForm key:[NSString stringWithFormat:@"%@.json", _workTime] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        //        NSLog(@"波形:%@", resp);
        state.waveUrl = [resp valueForKey:@"url"];
        state.waveUploadId = [resp valueForKey:@"uploadId"];
        NSString *statePath =[_workSpace stringByAppendingPathComponent:@"workState"];
        [NSKeyedArchiver archiveRootObject:state toFile:statePath];
    } option:option];
}

- (void)UpLoadImageNameArray:(NSArray *)imageNameArray ImagePathArray:(NSArray *)imagePathArray
{
    NSLog(@"%@", imageNameArray);
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"2" forKey:@"type"];
    [manager GET:@"http://pillele.cn/api/uptoken" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        NSString *token = [dic objectForKey:@"token"];
        //        NSLog(@"成功：%@", _token);
        [self UpLoadImg:imagePathArray imageName:imageNameArray token:token];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)UpLoadImg:(NSArray *)imagePath imageName:(NSArray *)imageName token:(NSString *)token{
    NSMutableDictionary *optionDic = [NSMutableDictionary dictionary];
    [optionDic setObject:@"2" forKey:@"x:type"];
    [optionDic setObject:[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] forKey:@"x:uid"];
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:nil params:optionDic checkCrc:NO cancellationSignal:nil];
    QNUploadManager *manager = [[QNUploadManager alloc] init];
    [self uploadAgainwithPath:imagePath[i] name:imageName[i] time:[_tag_imageArray[i] valueForKey:@"timeline"] token:token manager:manager option:option];
}
- (void)uploadAgainwithPath:(NSString *)path name:(NSString *) name time:(NSString *)time token:(NSString *)token manager:(QNUploadManager *)manager option:(QNUploadOption *)option{
    NSLog(@"name == %@", name);
    [manager putFile:path key:name token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//                NSLog(@"%@,%@,%@,%@",name, info,key,resp);
//                NSLog(@"%@", key);
//                NSLog(@"%@", resp);
        if (resp == nil) {
            [self uploadAgainwithPath:path name:name time:time token:token manager:manager option:option];
        } else {
//            NSLog(@"%@", resp);
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[resp valueForKey:@"url"], @"url", [resp valueForKey:@"uploadId"], @"uploadId", time ,@"timeline",nil];
            NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *ImageString  = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [_tag_uploadImageArray addObject:ImageString];
            //            NSLog(@"上传图片个数：%d", [_tag_uploadImageArray count]);
//            if (_tag_imagePathArray.count > _tag_imageArray.count) {
//                
//                [_tag_imagePathArray removeLastObject];
//            }
            if (i < _tag_imagePathArray.count-1) {
                i++;
                [self uploadAgainwithPath:_tag_imagePathArray[i] name:_tag_imageNameArray[i] time:[_tag_imageArray[i] valueForKey:@"timeline"] token:token manager:manager option:option];
            }
            if (_tag_uploadImageArray.count == _tag_imagePathArray.count) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadPercent" object:[NSNumber numberWithFloat:0.9999]];
                if ([state.state isEqualToString:@"success"]) {
                    //                    NSLog(@"可以创建");
                    [self addInforToDic];
                } else {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"uploadState" object:@"false"];
                }
            }
        }
    } option:option];
}
- (void)addInforToDic{
    NSString *topic = [AppDelegate shareDelegate].topicString;
    if (topic != NULL) {
        [_tagArray addObject:[AppDelegate shareDelegate].topicString];
    }
    if ([AppDelegate shareDelegate].startTag != nil) {
        [_tagArray addObject:[AppDelegate shareDelegate].startTag];
    }
    self.tags = [_tagArray componentsJoinedByString:@","];
    [_allInfo setObject:_name forKey:@"title"];
    [_allInfo setValue:_tags forKey:@"tags"];
    if ([AppDelegate shareDelegate].topicDetailString.length > 0) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[AppDelegate shareDelegate].topicDetailString,@"topicDetail",[AppDelegate shareDelegate].topicString,@"topicName",[AppDelegate shareDelegate].topicIsPrivate,@"topicIsPrivate", nil];
        [_allInfo setValue:dic forKey:@"topicDetail"];
    }
//    if ([AppDelegate shareDelegate].topicIsPrivate) {
//        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[AppDelegate shareDelegate].topicIsPrivate,@"topicIsPrivate",[AppDelegate shareDelegate].topicString,@"topicName", nil];
//        [_allInfo setValue:dic forKey:@"topicIsPrivate"];
//    }
    [_allInfo setValue:_tag_audioSecond forKey:@"duration"];
    [_allInfo setValue:_tag_uploadImageArray forKey:@"images"];
    if (_tag_textArray.count > 0) {
        [_allInfo setValue:_tag_textArray forKey:@"texts"];
    }
    if (_tag_personArray.count > 0) {
        NSArray *ara = [NSArray arrayWithArray:_tag_personArray];
        [_tag_personArray removeAllObjects];
        for (NSDictionary *dic in ara) {
            NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *dicStr  = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [_tag_personArray addObject:dicStr];
        }
        [_allInfo setValue:_tag_personArray forKey:@"persons"];
    }
    [_allInfo setValue:_priceNum forKey:@"price"];
    [_allInfo setValue:_isPrivate forKey:@"isPrivate"];
    [_allInfo setValue:state.uploadId forKey:@"uploadId"];
    [_allInfo setValue:state.url forKey:@"url"];
    [_allInfo setValue:state.waveUrl forKey:@"waveform"];
    [_allInfo setValue:[NSNumber numberWithFloat:self.coordinate.longitude] forKey:@"locationX"];
    [_allInfo setValue:[NSNumber numberWithFloat:self.coordinate.latitude] forKey:@"locationY"];
    [_allInfo setValue:self.location forKey:@"location"];
    [self createWork:[NSNumber numberWithInteger:1]];
//    NSLog(@"%@", _allInfo);
}
- (void)createWork:(NSNumber *)count{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:@"http://123.57.1.143/api/work/create" parameters:_allInfo progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"uploadState" object:@"success"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:_workSpace error:nil];
        NSLog(@"++++%@", responseObject);
        [[NSUserDefaults standardUserDefaults] setValue:[[responseObject valueForKey:@"data"] valueForKey:@"tmpfile"] forKey:@"tmpfile"];
        [AppDelegate shareDelegate].topicIsPrivate = nil;
        [AppDelegate shareDelegate].topicString = nil;
        [AppDelegate shareDelegate].topicDetailString = nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSNumber *cou = count;
        if (cou.integerValue < 3) {
            cou = [NSNumber numberWithInteger:count.integerValue + 1];
            [self createWork:cou];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"uploadState" object:@"false"];
        }

    }];
}

@end
